var liveroom = require('../../wxcomponents/mlvb-live-room/mlvbliveroomcore.js');

const app = getApp()
// const computedBehavior = require('miniprogram-computed')
// import computedBehavior from 'miniprogram-computed'
// wx.$app.isTextMsg = false
// 没使用到
var errorCode = [{
		'-9001': '创建房间失败'
	},
	{
		'-9002': '获取推流地址失败'
	},
	{
		'-9003': '进入房间失败'
	},
	{
		'-9004': '请求连麦失败'
	},
	{
		'-9005': '发送消息失败'
	},
	{
		'-9006': '房间已经解散了'
	},
]

var _this = null;
var gListMenus = [{
		name: '静音'
	},
	{
		name: '美颜'
	},
	{
		name: '相机'
	},
	{
		name: '连麦'
	}
]
Component({
	// behaviors: [computedBehavior],
	options: {
		multipleSlots: true // 启用多slot支持
	},

	properties: {
		isLink: {
			type: Boolean,
			value: true
		},
		isStart: {//判断是否开始直播，false未开播
			type: Boolean,
			value: true
		},
		isZoom: {
			type: Boolean,
			value: false,
		},
		anchorLock: {
			type: Object,
			value: {}
		},
		itemRoom: {
			type: Object,
			value: {}
		},
		chatMixed: {
			type: Object,
			value: {}
		},
		chatTop: {
			type: Number,
			value: 0
		},
		chatList: {
			type: Array,
			value: []
		},
		canvasAud: {
			type: String,
			value: 'anchor'
		},
		roleL: {
			type: String,
			value: 'audience'
		},
		roomid: {
			type: String,
			value: '',
			observer: function(newVal, oldVal) {
				this.data.roomID = newVal;
			}
		},
		roomname: {
			type: String,
			value: 'undefined'
		},
		debug: {
			type: Boolean,
			value: false
		},
		template: {
			type: String,
			value: 'float'
		},
		beauty: {
			type: Number,
			value: 5
		},
		mutedPlayer: {
			type: Boolean,
			value: false
		},
		mutedPusher: {
			type: Boolean,
			value: false
		},
		pureaudio: {
			type: Boolean,
			value: false
		},
		payRoomId: {
			type: Number,
			value: 0
		},
		isBut:{
			type:Boolean,
			value:false
		}
	},

	data: {
		playsAddress: '',
		isCaster: false,//判断是否为主播，true-主播，false-观众
		menuItems: [],
		userName: '',
		userID: '',
		roomID: '',
		pusherContext: null,
		playerContext: null,
		linkedPlayerContext: null,
		unload: 1,
		isInRoom: 0,
		unfold: false,
		mainPusherInfo: {
			url: '',
			aspect: '3:4',
			minBitrate: 200,
			maxBitrate: 300,
			puserID: '',
		},
		audience: {
			url: null,
			mixUrl: null,
			accelerateUrl: null,
			pusherName: '',
			pusherID: '',
			isLinked: false,
			aspect: '3:4',
			loading: false,
			objectFit: false
		},
		linkPusherInfo: {
			url: '',
			loading: true,
			debug: true,
		},
		members: [],
		visualPlayers: [],

		mode: 'RTC',
		headerHeight: app.globalData.headerHeight,
		statusBarHeight: app.globalData.statusBarHeight,
		quitLinking: false,
		chinaFlag: 'http://www.huihejituan.com/tripPictstorage/nationalflag/China.png',
		isLockInvite: false, // 锁定和邀请弹框
		isAnchorInfo: false, // 主播信息弹框
		isListener: false, // 底部遮罩层
		numberLink: 0,
		lockNumber: 0,
		nowAnchorInfo: {},
		memberid: 0,
		isZoomPlayer: false,
		isZoomPusher: false,
		isZoomMember: 0,
		zoomInAnchor: '',
		anchorID: 0,
		timerImg:'http://www.huihejituan.com/tripPictstorage/qmore/wx/5a0cdc8c3647a58c2b1c0b803d9b1bf.png',
		h: '00',
		m: '00',
		s: '00',
		isClear:false
	},

	methods: {
		setBlack() {
			this.setData({
				isListener: true
			})
		},
		memberlist(){
			console.log(this.data.roomID,'成员列表')
			wx.navigateTo({
				url: '../memberlist/memberlist?group_id='+this.data.payRoomId+'&roomID='+this.data.roomID+'',
			})
		},
		onClcik() {

			console.log('tim', wx.$app)
			let group = wx.getStorageSync('liveRoomID')
			let promiseMemberList = wx.$app.getGroupMemberList({
				groupID: group,
				count: 30,
				offset: 0
			}); // 从0开始拉取30个群成员
			promiseMemberList.then(function(imResponse) {
				console.log(imResponse.data.memberList, '群成员列表？'); // 群成员列表
			}).catch(function(imError) {
				console.warn('getGroupMemberList error:', imError);
			});

		},
		deleteMember() {
			let group = wx.getStorageSync('liveRoomID')
			let promiseDetele = wx.$app.deleteGroupMember({
				groupID: group,
				userIDList: ['9163'],
				reason: 'lalala'
			});
			promiseDetele.then(function(imResponse) {
				console.log(imResponse.data.group, '1'); // 删除后的群组信息
				console.log(imResponse.data.userIDList, '1'); // 被删除的群成员的 userID 列表
			}).catch(function(imError) {
				console.warn('deleteGroupMember error:', imError); // 错误信息
			});
		},
		liveAddress(event) {
			let self = this
			let num = parseInt(event.target.dataset.number)
			console.log(event,'是什么样的值')
			if(self.data.isStart){
				self.theStart();
			}else{
				if (!self.data.isCaster) {
					// 连麦(观众) 0.1  触发连麦事件
					let numIndex = num == 1 ? 0 : num;
					if (self.data.chatMixed.msg[numIndex]) { //看不懂这个判断是什么意思GL,主要是不懂onAnchroInfo()是什么方法
						wx.setStorageSync('number', num)
						self.requestJoinAnchor()
					} else if (!self.data.anchorLock.msg[num - 1]) {
						self.onAnchorInfo({}, num);
					} else {
						wx.showToast({
							title: '该位置主播已锁定',
							icon: 'none'
						})
					}
				} else {
					self.setData({
						isListener: true,
						isLockInvite: true,
						numberLink: num
					})
				}
			}
			
		},
		bindLockAddress(event) {
			this.setData({
				lockNumber: event.currentTarget.dataset.locknumber
			})
			let isMsg = this.data.anchorLock.msg[this.data.lockNumber] ? true : false
			if (isMsg) {
				this.unlockAddress(this.data.lockNumber)
			} else {
				this.lockAddress(this.data.lockNumber)
			}
		},
		lockAddress(lockNumber) {
			let self = this;
			let newAnchorLock;
			self.data.anchorLock.msg[lockNumber] = '123';
			newAnchorLock = JSON.parse(JSON.stringify(self.data.anchorLock));
			newAnchorLock.msg = JSON.stringify(newAnchorLock.msg);
			self.sendChat(JSON.stringify(newAnchorLock), false);
			self.setData({
				anchorLock: self.data.anchorLock,
			})
			self.listener()
		},
		unlockAddress(lockNumber) {
			let self = this;
			let newAnchorLock;
			delete self.data.anchorLock.msg[lockNumber]
			newAnchorLock = JSON.parse(JSON.stringify(self.data.anchorLock));
			newAnchorLock.msg = JSON.stringify(newAnchorLock.msg)
			self.sendChat(JSON.stringify(newAnchorLock), false)
			self.setData({
				anchorLock: self.data.anchorLock,
			})
			self.listener()
		},
		listener() {
			this.setData({
				isLockInvite: false,
				isAnchorInfo: false,
				isListener: false
			})

			this.sendTrig('hideGift', {
				isGift: false
			})
			console.log("执行了？")
		},
		onSendGift() {
			this.setBlack()
			// this.onZoomOut()
			this.sendTrig('hideGift', {
				isGift: true,
				payment_id: this.data.anchorID,
			})
		},
		onSendChat() {
			this.sendTrig('chat', false)
		},
		onAnchorInfo(event, memberIndex) {
			let self = this;
			if (!self.data.isZoomPusher) {
				let str = memberIndex ? memberIndex : event.currentTarget.dataset.anchorindex;
				let index = memberIndex ? memberIndex : str.charAt(str.length - 1)
				index = index == 1 ? 0 : index
				self.data.anchorID = self.data.chatMixed.msg[index].userId
				self.data.isZoomPlayer = 'http://live.curiousmore.com/live/1400255047_' + self.data.anchorID + '.flv'
					
				wx.$app.myAjaxNew({
					model: 'user',
					controllerName: 'userInfo',
					actionName: 'query',
					notLoading: true,
					data: {
						user_id: self.data.anchorID
					},
					successBack: function(res) {
						if (!res.data.code) {
							let nowYear = new Date().getFullYear()
							let info = res.data.data[0]
							let itemInfo = {
								avatar: info.avatar,
								intro: info.intro || '暂无签名',
								natFlag: info.national_flag || self.data.chinaFlag,
								sex: info.sex,
								country: info.country || '中国',
								nickName: info.nick_name || 'Q小陌',
								city: info.city || '杭州',
								distance: info.distance || 0,
								memberLevel: info.member_level || 0,
								age: nowYear - parseInt(info.birth.split('-')[0]),
								masterType: info.master_type || 0
							}
							self.setData({
								nowAnchorInfo: itemInfo,
								isListener: true,
								isAnchorInfo: true,
							})
						}

					},
				})
			}

		},
		onJoinFriend() {
			let self = this;
			self.onZoomOut()
			wx.$app.myAjaxNew({
				model: 'user',
				controllerName: 'userOrder',
				actionName: 'queryFreeFriendsCount',
				notLoading: true,
				data: {
					user_id: wx.getStorageSync('user_id')
				},
				successBack: function(res) {
					console.log(res, '查询当前加好友的次数？')
					if (!res.data.code) {
						wx.showModal({
							content: '你需要送1份见面礼表示诚意(每天3次加好友免费，还剩' + res.data.data.freeCount + '次)',
							cancelText: '取消',
							confirmText: '确定',
							success: function(sm) {
								if (sm.confirm) {
									console.log(sm, '同意了')
									self.joinFriend()
								} else if (sm.cancel) {
									console.log(sm, '拒绝了')
								}
							}
						})
					}
				},
			})
		},
		joinFriend() {
			let self = this
			wx.$app.myAjaxNew({
				model: 'user',
				controllerName: 'userOrder',
				actionName: 'updateFreeFriends',
				notLoading: true,
				data: {
					pay_id: self.data.payRoomId,
					type: 'gift',
					type_id: '1',
					payment_id: self.data.anchorID,
					user_id: wx.getStorageSync('user_id')
				},
				successBack(res) {
					if (res.data.data.result) {
						wx.showToast({
							title: '已发送',
							icon: 'none'
						})
					}
				}
			})
		},
		onShowDetail() {
			this.onZoomOut()
			wx.navigateTo({
				url: '/pages/My/myDetails/myDetails?user_id=' + this.data.anchorID
			})

		},
		onMemberInfo(event) {
			let self = this
			let index = event.currentTarget.dataset.membernumber
			self.data.isZoomMember = index
			self.onAnchorInfo({}, index)
			self.setData({
				memberid: event.currentTarget.dataset.memberid,
			})
		},
		exitLink() {
			let self = this
			self.listener()
			if (self.data.isCaster) {
				let obj = {
					data: {
						userID: self.data.memberid
					},
					success: function(res) {
						console.log('踢人连麦发送消息成功？', res)
					},
					fail: function(err) {}
				}
				liveroom.kickoutJoinAnchor(obj)
			} else {
				let num = wx.getStorageSync('number')
				self.data.chatMixed.msg[num] = ''
				self.setData({
					chatMixed: self.data.chatMixed,
					canvasAud: 'anchor'
				})
				let keys = Object.keys(self.data.chatMixed.msg)
				keys.forEach(key => {
					self.data.chatMixed.msg[key] = JSON.stringify(self.data.chatMixed.msg[key])
				})
				self.data.chatMixed.msg = JSON.stringify(self.data.chatMixed.msg)
				self.sendChat(JSON.stringify(self.data.chatMixed), true)
			}

		},
		onZoomIn() {
			let self = this
			if (!self.data.isCaster) {
				if (self.data.playsAddress) {
					self.setData({
						isZoom: true,
						isZoomPusher: true
					})
				} else {
					self.setData({
						isZoom: true,
						isZoomPlayer: self.data.isZoomPlayer
					})
				}

			} else {
				self.setData({
					isZoom: true,
					isZoomMember: self.data.isZoomMember

				})
			}
			self.triggerEvent('RoomEvent', {
				tag: 'hideButton',
				code: 0,
				detail: true
			})
			self.listener()
		},

		onZoomOut() {
			if (this.data.isZoomPlayer) wx.createLivePlayerContext('zoomplayer', this).stop();
			this.setData({
				isZoom: false,
				isZoomPusher: false,
				isZoomMember: 0,
				isZoomPlayer: ''
			})
			this.triggerEvent('RoomEvent', {
				tag: 'hideButton',
				code: 0,
				detail: false
			})
			this.listener()
		},
		sendTrig(tag, detail) {
			this.triggerEvent('RoomEvent', {
				tag: tag,
				code: 0,
				detail: detail
			})
			console.info(tag);
		},
		onStart() {
			//isCaster 判断是否为主播T-主播 F-观众  
			//isStart 判断是否开播 T-开播 F-未开播
			//isClear 清除连线中计时
			console.log(this.data.isCaster,'我是什么')
			this.sendTrig('start', false);  //到MLVBRoom.vue 819行
			if(this.data.isStart){
				this.setData({
					isClear:false
				})
				this.liveTimer()//连线中的计时
			}else{
				this.setData({
					isClear:true
				})
			}
		},
		invitationWheat(){//邀请连麦
			console.log(this.data.isStart,'我邀请你连麦呀')
			if(this.data.isStart){
				wx.showToast({
					title:'请先开播',
					icon:'none'
				})
			}else{
				var TheIS = true
				wx.navigateTo({
					url: '../memberlist/memberlist?group_id='+this.data.payRoomId+'&roomID='+this.data.roomID+'&IsHost='+TheIS+'',
				})
			}
		},
		theStart(){
			if(this.data.isStart){
				wx.showToast({
					title: '请先连线',
					icon: 'none'
				})
			}else{
				this.onStart()
			}
		},
		onMutedPlayer() {
			this.sendTrig('player', false)
			console.log("player")
		},
		onMutedPusher() {
			this.sendTrig('pusher', false)
		},
		onCamera() {
			let self = this
			self.switchCamera()
		},
		onTimerImg(){
			let self = this
			let list = [
				'http://www.huihejituan.com/tripPictstorage/qmore/wx/0debd51ca7f29ad62d8055a9cc89645.png',
				'http://www.huihejituan.com/tripPictstorage/qmore/wx/d811645b030b3c5abd8b44d9981354a.png',
				'http://www.huihejituan.com/tripPictstorage/qmore/wx/225f413aec74d0afe8a8cbb83858d17.png',
				'http://www.huihejituan.com/tripPictstorage/qmore/wx/6cad6c9fc6e1e1a5b92bf954a35a3b6.png',
				'http://www.huihejituan.com/tripPictstorage/qmore/wx/3df01c2d7a2caffac8a374d3a599d2a.png',
				'http://www.huihejituan.com/tripPictstorage/qmore/wx/fe1249f84854051fdc5706377e0ad1d.png',
				'http://www.huihejituan.com/tripPictstorage/qmore/wx/04a49f7e993c3217b68c01b865cfdd7.png',
				'http://www.huihejituan.com/tripPictstorage/qmore/wx/29f82e6fbd6010dd094220b137367e0.png',
				'http://www.huihejituan.com/tripPictstorage/qmore/wx/ce51a99c9c1cb5295153d1832d492b5.png'
			]
			let num = 0
			let timer = setInterval(() =>{
				
				self.setData({
					timerImg: list[num]
				})
				num++
				if(num == 10) clearInterval(timer)
			}, 1000)
		},
		liveTimer(){
			let self = this
			let hTime = 0;
			let mTime = 0;
			let sTime = 0;
			let liveTimer = setInterval(() =>{
				// console.log(sTime, '直播时长？')
				sTime++
				if(self.data.isClear){
					clearInterval(liveTimer)
				} else if(sTime == 60) {
					mTime++
					sTime = 0
				}else if(mTime == 60){
					hTime++
					mTime = 0
					hTime = 0
				} 
				self.setData({
					h: hTime < 10 ? '0' + hTime : hTime,
					m: mTime < 10 ? '0' + mTime : mTime,
					s: sTime < 10 ? '0' + sTime : sTime
				})
			}, 1000)
		},
		sendChat(data, isQuit) {
			let self = this
			let toID = wx.getStorageSync('liveRoomID').toString()
			let message = wx.$app.createCustomMessage({
				to: toID,
				conversationType: 'GROUP',
				payload: {
					data: data,
					description: '',
					extension: '',
				}
			});
			let customPromise = wx.$app.sendMessage(message);
			customPromise.then(function(imResponse) {
				console.log(imResponse, '锁定位置？')
				isQuit && self.quitLink()
			}).catch(function(imError) {
				console.warn('sendMessage error:', imError);
			});
		},
		toggleDebug() {
			var self = this;
			self.setData({
				debug: !self.data.debug
			}, () => {
				console.log('>> Debug: ', self.data.debug);
			})
		},
		toggleBeauty() {
			var self = this;
			var bty = self.data.beauty == 5 ? 0 : 5;
			self.setData({
				beauty: bty
			}, () => {
				console.log(bty > 0 ? '开启美颜' : '关闭美颜')
			})

		},
		toggleMuted() {
			var self = this;
			self.setData({
				mutedPlayer: !self.data.mutedPlayer
			}, () => {
				console.log(self.data.mutedPlayer ? '静音' : '非静音')
			})
		},
		clipPusherIDs() {
			var self = this;
			var data = '';
			var main = '';
			var link = '';
			if (self.data.mainPusherInfo.url) main = substring(aa.lastIndexOf('/') + 1, aa.indexOf('?'))
			if (self.data.linkPusherInfo.url) link = substring(aa.lastIndexOf('/') + 1, aa.indexOf('?'))
			data = `MAIN: ${main}; LINK: ${link}`
			wx.setClipboardData({
				data: data,
				success: function(res) {
					wx.showToast({
						title: `复制成功`,
						duration: 500,
						mask: true,
					})
				}
			})
		},
		unfoldCtrlMenu() {
			var self = this;

			var items = self.data.menuItems;
			if (items.length > 0) {
				items = [];
			} else {
				items = gListMenus;
			}
			self.setData({
				menuItems: items,
				unfold: !self.data.unfold
			}, () => {
				wx.showToast({
					title: items.length > 0 ? 'unfold' : 'close',
					duration: 500,
					mask: true,
				})
			})
		},
		selectMenu(e) {
			var self = this;
			var index = e.currentTarget.dataset.index;
			wx.showToast({
				title: `选中 ${index}: ${self.data.menuItems[index]}`,
				duration: 500,
				mask: true,
			})
		},
		// 发送文本信息 -1(文本聊天消息)
		sendTextMsg(text) {
			var self = this;
			if (text.startsWith('>')) {
				switch (text) {
					case '>debug':
						{
							self.toggleDebug();
							return;
						}
				}
			}
			// 发送消息方法  -1.1(文本聊天消息)
			liveroom.sendRoomTextMsg({
				data: {
					msg: text
				},
				success: () => {},
				fail: (e) => {
					console.log("发送消息失败: ", e)
					self.triggerEvent('RoomEvent', {
						tag: 'error',
						code: -9005,
						detail: `发送消息失败`
					})
				}
			});
		},

		switchCamera() {
			var self = this;
			console.log('切换摄像头: ', self.data.pusherContext)
			self.data.pusherContext && self.data.pusherContext.switchCamera({});
		},

		// 连麦(主播) 0.7 主播同意或拒绝
		respondJoinAnchor(agree, audience) {
			console.info(`respondJoinAnchor(agree:${agree}, audience:${audience}) called`)
			var self = _this;
			if (agree) {
				// 0.7.1 同意入口
				liveroom.acceptJoinAnchor({
					data: audience
				});
			} else {
				// 0.7.2 拒绝入口
				liveroom.rejectJoinAnchor({
					data: audience
				});
			}
		},

		setupLiveRoomListener() {
			var self = this;
			liveroom.setListener({
				onRoomDestroy: self.onRoomDestroy,
				onRecvRoomTextMsg: self.onRecvRoomTextMsg,
				onSketchpadData: self.onSketchpadData,
				onKickoutJoinAnchor: self.onKickoutJoinAnchor,
				onRequestJoinAnchor: self.onRequestJoinAnchor,
				onAnchorExit: self.onAnchorExit,
				onAnchorEnter: self.onAnchorEnter
			});
		},

		start: function() {
			console.info('start() called')
			var self = this;
			if (!self.data.isCaster) { //观众
				console.log('观众')
				// 观众 一.  enter进房方法
				self.enter();  //到931行
			} else { //主播
				console.log('主播')
				// 主播 1. getPushURL, 获取推流地址
				wx.setStorageSync('isCaster', self.data.isCaster)
				liveroom.getPushURL({
					success: function(ret) {
						console.log('getPushURL 成功，', ret)
						self.data.mainPusherInfo.url = ret.pushURL
						self.setData({
							mainPusherInfo: self.data.mainPusherInfo
						}, function() {
							self.setupLiveRoomListener();
							self.data.pusherContext = wx.createLivePusherContext('pusher', self);
							console.warn('创建 pusherContext：', self.data.pusherContext);
							// 1.1 开始推流
							self.data.pusherContext.start();
							
						});
					},
					fail: function(ret) {
						console.log('获取推流地址失败: ', ret);
						self.triggerEvent('RoomEvent', {
							tag: 'error',
							code: -9002,
							detail: `获取推流地址失败`
						})
					}
				});
			}
		},



		stop() {
			console.log('stop() called');
			var self = this;
			self.data.playerContext = wx.createLivePlayerContext('player', self);
			console.log('stop pusherContext：', self.data.pusherContext, self.data.playerContext);
			self.data.pusherContext && self.data.pusherContext.stop();
			self.data.playerContext && self.data.playerContext.stop();
			var players = self.data.members;
			players && players.forEach(p => {
				p.context && p.context.stop()
			});
			// 重置信息
			self.setData({
				unload: 1,
				members: [{}],
				visualPlayer: [],
				pusherContext: null,
				playerContext: null,
				linkedPlayerContext: null,
			});
			self.exit();
			liveroom.setListener({});
		},
		pause() {
			console.log('pause() called');
			var self = this;
			self.data.pusherContext && self.data.pusherContext.pause();
			self.data.playerContext && self.data.playerContext.pause();
		},
		resume() {
			console.log('resume() called');
			var self = this;
			self.data.pusherContext && self.data.pusherContext.resume();
			self.data.playerContext && self.data.playerContext.resume();
		},

		onAnchorEnter(ret) {
			console.log('==> onPusherJion() called: ', ret)
			var self = _this;
			var temp = self.data.members.filter(e => e.userID);
			var pushers = ret.pushers;
			//去掉自己
			var index = pushers.map(p => p.userID).indexOf(self.data.userID);
			if (index != -1) pushers.splice(index, 1);
			//去掉主播
			index = pushers.map(p => p.userID).indexOf(self.data.audience.pusherID);
			if (index != -1) pushers.splice(index, 1);

			console.log(`%c===> ${pushers.length} 人加入Link`, "color: yellow")
			console.log(pushers,'我就是想要获取图片')
			pushers = pushers.map(p => {
				return {
					userID: p.userID,
					userName: p.userName,
					accelerateURL: p.accelerateURL,
					userAvatar:p.userAvatar,
					context: null,
					number: wx.getStorageSync('number')
				}
			});
			temp = temp.concat(pushers);
			console.log('设置推流模式为:RTC');
			self.setData({
				members: temp
				// mode: 'RTC'
			}, function() {
				temp.forEach(p => {
					if (p.context) return;
					if (p.userID) p.context = wx.createLivePlayerContext(p.userID, self)
				})
				console.log('data.members: ', self.data.members)
				self.setData({
					canvasAud: self.data.members.length + 'anchor'
				})
			})
		},

		onAnchorExit(ret) {
			console.log('===> onAnchorExit() called: ', ret)
			var self = _this;
			var temp = [];
			var pushers = ret.pushers;
			var members = self.data.members;
			for (var p of pushers) {
				for (var i in members) {
					if (p.userID == members[i].userID) {
						members[i].context && members[i].context.stop();
						members.splice(i, 1);
						members.push({});
						break;
					}
				}
			}

			// var mode = 'SD';
			// for (var i=0; i<members.length; ++i) {
			//     if (members[i].userID) {
			//         mode = 'RTC';
			//     }
			// }
			// console.log('设置推流模式为:', mode);

			self.setData({
				members: members
				// mode: mode
			}, () => {
				console.log('members after onAnchorExit: ', self.data.members)
			})
		},
		onRequestJoinAnchor(pusher) {
			var self = _this;
			console.log('onRequestJoinAnchor() called, pusher = ', JSON.stringify(pusher))
			// 连麦(观众) 0.5 触发标签事件(mlvb-live-room标签)
			self.triggerEvent('RoomEvent', {
				tag: 'requestJoinAnchor',
				code: 0,
				detail: pusher
			})
		},
		onKickoutJoinAnchor() {
			console.log('onKickoutJoinAnchor() called')
		},
		enter() {
			var self = this;
			liveroom.setListener({
				onRoomDestroy: self.onRoomDestroy,
				onRecvRoomTextMsg: self.onRecvRoomTextMsg,
				onSketchpadData: self.onSketchpadData,
				onAnchorExit: self.onLinkPusherQuit,
				onAnchorEnter: self.onAnchorEnter,
				onKickoutJoinAnchor: self.onKickoutJoinAnchor
			});
			let liveRoomID = wx.getStorageSync('liveRoomID')
			var data = {
				roomID: liveRoomID
			}
			// 一.1 执行进房方法enterRoom
			liveroom.enterRoom({  //mlvbliveroomcore.js 1037
				data,
				success: function(ret) {
					console.info('enterRoom 成功: ', ret)
					self.data.audience.url = ret.mixedPlayURL;
					self.data.audience.mixUrl = ret.mixedPlayURL;
					self.data.mainPusherInfo.puserID = ret.roomCreator;
					if (ret.pushers && ret.pushers.length > 0) {
						self.data.audience.pusherName = ret.pushers[0].userName;
						self.data.audience.pusherID = ret.pushers[0].userID;
						self.data.audience.accelerateUrl = ret.pushers[0].accelerateURL;
					} else {
						console.error('缺少加速流');
					}
					//{ "cmd":"C2CCustomMsg", "data":{ userName: "xxx", userAvatar:"xxx", "roomID":"XXX", "cmd":"xx", msg:"xx" } }
					// liveroom.sendC2CCustomMsg({
					// 	cmd: "sketchpad",
					// 	msg: '{"type":"request", "action":"currentPPT"}'
					// })
					// 一.8 进群进房成功后 将房间信息和拉流地址赋值
					self.playMixedUrl().then(() => {
						console.log('playMixedUrl done');
					}).catch(e => {
						console.log('playMixedUrl Error: ', e)
					});
				},
				fail: function(ret) {
					console.error('enterRoom 失败: ', ret)
					if (!self.data.unload) {
						self.data.playerContex && self.data.playerContext.stop();
						console.log(self.data);						
						self.setData({
							isClear:true,
							isStart:true
						});
						self.triggerEvent('RoomEvent', {
							tag: 'error',
							code: -9003,
							detail: 'enterRoom 失败'
						})
					}
				}
			});
		},

		create() {
			// 主播 3. 创建房间入口
			console.log('create() called')
			var self = this;
			var createRoomInfo = {
				roomInfo: self.data.roomname,
				pushURL: self.data.mainPusherInfo.url
			};
			if (self.data.roomID && self.data.roomID.length > 0) {
				createRoomInfo.roomID = self.data.roomID;
			}
			// console.log('创建房间参数：', createRoomInfo)

			// 3.1 调用创建房间方法
			liveroom.createRoom({
				data: createRoomInfo,
				success: function(ret) {
					console.log('创建房间成功, ret = ', ret)
					self.setData({
						roomID: ret.roomID
					})
					// 返回创建房间成功信息
					self.triggerEvent('RoomEvent', {
						tag: 'created',
						code: 0,
						detail: '创建房间成功'
					})
				},
				fail: function(ret) {
					console.error("创建房间失败", ret);
					if (!self.data.unload) {
						self.data.pusherContext.stop();
					}
					self.triggerEvent('RoomEvent', {
						tag: 'error',
						code: -9001,
						detail: '创建房间失败'
					})
				}
			});
		},

		exit: function() {
			console.log('exit() called')
			console.log(this)
			let self = this
			this.setData({
				mainPusherInfo: {
					url: '',
					aspect: '3:4',
					minBitrate: 200,
					maxBitrate: 300,
					puserID: '',
				},
				visualPlayers: [],
				linkPusherInfo: {
					url: '',
					loading: true,
					debug: true,
				},
				members: [],
				chatMixed: {
					cmd: 'AnchorIndex',
					msg: {
						"0": {
							avatar: self.__data__.itemRoom.groupAvatar,
							userId: self.__data__.itemRoom.userId,
							nickName: self.__data__.itemRoom.groupName
						}
					}
				}
			})

			liveroom.exitRoom({});
		},

		onPlay(ret) {
			var self = this;
			console.error('拉流情况：', ret.detail.code);
			switch (ret.detail.code) {
				case -2301:
					{
						// 多次拉流失败
						console.error('多次拉流失败')
						self.triggerEvent('RoomEvent', {
							tag: 'error',
							code: ret.detail.code,
							detail: '多次拉流失败'
						});
						break;
					};
			}
		},

		linkJionPusher() {
			console.log("linkJionPusher() called")
			var self = this;
			if (!self.data.linkPusherInfo.url || !self.data.roomID) {
				console.warn("linkJionPusher() stop.");
				return;
			}
			if (self.data.quitLinking) {
				//正在退出连麦，所以不进行连麦操作
				console.warn("正在退出连麦");
				return;
			}
			// 连麦(观众) 0.13 连麦方法入口，加入推流
			liveroom.joinAnchor({
				data: {
					pushURL: self.data.linkPusherInfo.url,
					roomID: self.data.roomID
				},
				success: function() {
					console.log('连麦成功完成')
					if (self.data.isCaster == false) {
						// 连麦(观众) 0.15 触发标签事件(mlvb-live-room标签)
						self.setData({
							playsAddress: 'v-main-video' + wx.getStorageSync('number')
						})
						wx.setStorageSync('streamIdArray', [wx.getStorageSync('user_id')])
						self.triggerEvent('RoomEvent', {
							tag: 'linkOn',
							code: 0,
							detail: '连麦成功完成'
						})
					}
				},
				fail: function(e) {
					console.error('连麦失败: ', e)
					self.triggerEvent('RoomEvent', {
						tag: 'error',
						code: 0,
						detail: '连麦失败'
					})
				}
			})
		},

		playMixedUrl() {
			console.log("==> playMixedUrl")
			var self = _this;
			var players = [{
				debug: true,
				mute: false,
				url: self.data.audience.mixUrl,
				mode: 'live',
				maxCache: 3,
				minCache: 1,
				loading: false,
				objectFit: 'fillCrop',
				userName: self.data.audience.pusherName
			}]
			return new Promise((resolve) => {

				self.data.visualPlayers = players
				self.setData({
						visualPlayers: players
					},
					function() {
						resolve()
					})
			})
		},

		playAccelerateUrl() {
			console.info('playAccelerateUrl() called')
			var self = _this;
			var players = [{
				debug: true,
				mute: false,
				url: self.data.audience.accelerateUrl,
				mode: 'RTC',
				loading: false,
				objectFit: 'fillCrop',
				userName: self.data.audience.pusherName
			}]
			return new Promise((resolve) => {
				self.setData({
					visualPlayers: players
				}, function() {
					players[0].minCache = 0.1;
					players[0].maxCache = 0.3;
					self.setData({
						visualPlayers: players
					})
					self.data.playerContext = wx.createLivePlayerContext('player', self);
					resolve()
				})
			});
		},

		stopPlayUrl() {
			var self = _this;
			// self.data.playerContext && self.data.playerContext.stop();
			return new Promise((resolve) => {
				self.setData({
					visualPlayers: [],
				}, function() {
					resolve()
				})
			});
		},

		getPushUrl() {
			console.info('getPushUrl() called')
			var self = _this;
			return new Promise(function(resolve, reject) {
				liveroom.getPushURL({
					success: function(ret) {
						console.log('getPushURL() 成功，', ret);
						resolve(ret.pushURL)
					},
					fail: function(e) {
						console.log('getPushUrl() 获取推流地址失败: ', e);
						reject(e)
					}
				});
			})
		},
		startLinkPush(url) {
			console.info('startLinkPush() called')
			var self = _this;
			return new Promise(function(resolve, reject) {
				self.data.linkPusherInfo.url = url;
				self.data.members.splice(0, 1);

				// console.log('设置推流模式为:RTC');
				self.setData({
					members: self.data.members,
					linkPusherInfo: self.data.linkPusherInfo
					// mode: 'RTC'
				}, function() {
					self.data.pusherContext = wx.createLivePusherContext('audience_pusher', self);
					console.log('startLinkPush.创建 pusherContext：', self.data.pusherContext);
					self.data.pusherContext.start();
					resolve()
				});
			})
		},
		//连麦(观众) 0.11 停止播放流，触发推流
		link() {
			var self = this;
			//停止mix流播放 --> 播放 accelerate流 --> 获取推流连接开始推流 --> onLinkPush 成功后 jionPusher
			Promise.resolve()
				.then(self.stopPlayer) // 0.11.1 停止mix流播放
				.then(self.playAccelerateUrl) // 0.11.2 播放 accelerate流
				.then(self.getPushUrl) // 0.11.3 获取推流地址
				.then(self.startLinkPush) // 0.11.4 开始推流
				.then(function() {
					return new Promise(function(resolve, reject) {
						console.log('----> link() self.data: ', self.data)
						// 0.11.5 推流开始后，触发标签事件(live-pusher标签) 执行 onLinkPush方法
						resolve()
					})
				})
				.catch(function(e) {
					console.log("过程出错： 停止mix流播放 --> 播放 accelerate流 --> 获取推流连接开始推流 --> onLinkPush 成功后 jionPusher: ", e)
					self.triggerEvent('RoomEvent', {
						tag: 'error',
						code: -1,
						detail: '连麦过程发生错误'
					});
				})
		},
		requestJoinAnchor() {
			console.log('requestJoinAnchor() called')
			var self = _this;
			let requestLinking = wx.getStorageSync('requestLinking') || false;
			if (requestLinking) {
				wx.showToast({
					title: '等待大主播接受连麦',
					duration: 1000,
				})
				return;
			}
			console.log('用户请求连麦');
			console.log('用户请求连麦实时');
			wx.setStorageSync('requestLinking', true);
			let timer = setTimeout(() => {
				let isTimer = wx.getStorageSync('requestLinking');
				if (!isTimer) {
					clearTimeout(timer)
				} else {
					wx.setStorageSync('requestLinking', false)
					wx.showToast({
						title: '连麦超时',
						duration: 1000,
					})
				}
			}, 20000)
			// 连麦(观众) 0.2 连麦方法
			console.log(self.data.itemRoom,'房主Id')
			liveroom.requestJoinAnchor({				
				data: {
					timeout: 20000,
					roomCreator: self.data.itemRoom.userId//传入房主ID
				},
				success: function(ret) {
					wx.setStorageSync('requestLinking', false)
					console.log('请求连麦成功: ', ret)
					// 连麦(观众) 0.10 请求连麦成功后, 调用连麦方法
					self.link();
				},
				fail: function(e) {
					console.log('请求连麦失败: ', e)
					wx.setStorageSync('requestLinking', false)
					self.triggerEvent('RoomEvent', {
						tag: 'error',
						code: -9004,
						detail: e.errMsg
					})
				}
			});
		},

		onLinkError(e) {
			console.error("onLinkError() called: ", e)
			self.triggerEvent('RoomEvent', {
				tag: 'error',
				code: -2,
				detail: "播放错误"
			})
		},
		kickoutJoinAnchor(e) {
			console.log('kickoutJoinAnchor() called');
			var self = _this;
			console.log('==> kickoutJoinAnchor: ', e)
			var userID = e.currentTarget.dataset.userid;
			liveroom.kickoutJoinAnchor({
				data: {
					userID: userID
				},
				success: (ret) => {
					console.log("--> 踢人成功： ", ret)
					var members = self.data.members;
					var index = members.map(m => m.userID).indexOf(userID);
					if (index != -1) {
						// members[index].context && members[index].context.stop();
						members.splice(index, 1)
						members.push({})
					}
					self.setData({
						members: members
					})
					// self.members = members
					console.log('data.members: ', self.data.members)
				},
				fail: (e) => {
					console.log("---> 踢人失败： ", e)
				}
			})
			//todo
		},
		quitLink() {
			console.log('quitLink() called')
			var self = this;
			if (self.data.pusherContext == null || self.data.quitLinking) {
				console.warn("no need quitLink again")
				return;
			}
			self.data.quitLinking = true;
			liveroom.quitJoinAnchor({
				success: (ret) => {
					console.log('quitJoinAnchor 成功：', ret)
					self.resetToAudience();
					self.data.quitLinking = false;
				},
				fail: (e) => {
					console.error('quitJoinAnchor Error: ', e);
					self.resetToAudience();
					// self.triggerEvent('RoomEvent', {
					//     tag: 'error',
					//     code: -1,
					//     detail: '退出连麦"quitJoinAnchor"返回错误'
					// })
					self.data.quitLinking = false;
				}
			})
		},
		resetToAudience() {
			console.log('resetToAudience() called');
			var self = _this;
			Promise.resolve()
				.then(() => { // 停止推流
					console.log('停止推流')
					return new Promise((resolve) => {
						console.log('停止推流')
						self.data.pusherContext && self.data.pusherContext.stop();
						self.data.linkPusherInfo.url = null;
						self.setData({
							pusherContext: null,
							linkPusherInfo: self.data.linkPusherInfo
						}, () => resolve())
					})
				})
				.then(() => { // 清理member players
					console.log('清理 member players')
					return new Promise((resolve) => {
						var pushers = self.data.members;
						pushers && pushers.forEach(p => {
							p.context && p.context.stop()
						})
						pushers = [{}, {}, {}]
						self.setData({
							members: pushers
						}, () => resolve());
					});
				})
				.then(self.stopPlayUrl) // 停止播放 acelerate 流
				.then(self.playMixedUrl) //播放mixed 流
				.then(() => {
					return new Promise((resolve) => {
						self.triggerEvent('RoomEvent', {
							tag: 'linkOut',
							code: 0,
							detail: '连麦断开'
						})
						resolve();
					})
				})
				.catch((e) => {
					console.error('resetToAudience 流程出现错误：', e);
				})
		},
		onLinkPusherQuit(ret) {
			console.log('onLinkPusherQuit() called ', ret)
			var self = _this;
			var pushers = ret.pushers;
			if (!pushers) return;
			var userIndex = pushers.map(p => {
				return p.userID
			}).indexOf(self.data.userID);
			if (userIndex != -1) { // 自己退出link

				self.resetToAudience();
			} else { // 别人退出link
				self.onAnchorExit(ret);
			}
		},

		onKickoutJoinAnchor(ret) {
			console.log('onKickoutJoinAnchor() called');
			var self = _this;
			console.log('%c onKickoutJoinAnchor: ', 'color: red;', ret)
			self.quitLink();
		},

		onPushEvent(code) {
			var self = this;
			switch (code) {
				case -1301:
					{
						console.log('打开摄像头失败: ', code);
						self.triggerEvent('RoomEvent', {
							tag: 'error',
							code: -1301,
							detail: '打开摄像头失败'
						})
						break;
					};
				case -1302:
					{
						console.log('打开麦克风失败: ', code);
						self.triggerEvent('RoomEvent', {
							tag: 'error',
							code: -1302,
							detail: '打开麦克风失败'
						})
						break;
					};
				case -1307:
					{
						console.error('推流连接断开: ', code);
						// 推流连接断开就做退房操作
						self.exit();
						self.triggerEvent('RoomEvent', {
							tag: 'error',
							code: -1307,
							detail: '推流连接断开'
						})
						break;
					};
				case -1305:
					{
						console.log('不支持的视频分辨率');
						self.triggerEvent('RoomEvent', {
							tag: 'error',
							code: -1305,
							detail: '不支持的视频分辨率'
						})
						break;
					}
				case -1306:
					{
						console.log('不支持的音频采样率');
						self.triggerEvent('RoomEvent', {
							tag: 'error',
							code: -1306,
							detail: '不支持的音频采样率'
						})
						break;
					}
				default:
					{
						console.log('推流事件：', code);
						break;
					}
			}
		},
		// 连麦(观众) 0.12 实时获取推流情况
		onLinkPush(ret) {
			var self = this;
			console.log('onLinkPush推流情况：', ret.detail.code);
			switch (ret.detail.code) {
				case 1002:
					{
						console.log('onLinkPush推流成功：', ret.detail.code);
						// 0.12.1 推流成功后 加入连麦
						self.linkJionPusher();

						break;
					};
				case 5000:
					{
						console.log('收到5000: ', ret.detail.code);
						// 收到5000就退房
						self.exit();
						self.data.exit = 5000;
						self.triggerEvent('RoomEvent', {
							tag: 'error',
							code: 5000,
							detail: '收到5000就退房'
						})
						break;
					};
				default:
					{
						self.onPushEvent(ret.detail.code);
						break;
					}
			}

		},

		// 主播 2. 开始推流后，触发onMainPush
		onMainPush(ret) {
			var self = this;
			console.log('>> onMainPush() called: ', ret)
			console.log('推流情况：', ret.detail.code);
			switch (ret.detail.code) {
				case 1005:
					{
						console.log("推流动态分辨率改变： ", ret);
						break;
					}
				case 1002:
					{
						console.log('推流成功：', ret.detail.code);
						if (!self.data.isInRoom) {
							self.setData({
								isInRoom: 1
							});
							self.isInRoom = 1
							// 2.1 推流成功，请求CGI:create_room，获取roomID、roomSig

							self.create();
						}
						break;
					};
				case -1307:
					{
						console.error('推流连接断开: ', ret.detail.code);
						self.exit();
						self.data.exit = -1307;
						self.triggerEvent('RoomEvent', {
							tag: 'error',
							code: -1307,
							detail: '推流连接断开'
						})
						break;
					}
				case 5000:
					{
						console.log('收到5000: ', ret.detail.code);
						// 收到5000就退房
						self.exit();
						self.data.exit = 5000;
						self.triggerEvent('RoomEvent', {
							tag: 'error',
							code: 5000,
							detail: '收到5000就退房'
						})
						break;
					};
				default:
					{
						self.onPushEvent(ret.detail.code);
						break;
					}
			}
		},
		onMainError(e) {
			var self = this;
			console.error("onMainError called: ", e)
			self.triggerEvent('RoomEvent', {
				tag: 'error',
				code: -1,
				detail: e.detail && e.detail.errMsg || "推流错误"
			})
		},

		// 一.9 通过标签监听事件，返回 连接信息 
		onMainPlayState(e) {
			console.log('===> onMainPlayState: ', e)
			var self = this;
			//主播拉流失败不抛错误事件出去 
			if (self.data.isCaster == true) {
				return;
			}
			switch (e.detail.code) {
				case -2301:
					{
						// 多次拉流失败
						console.error('多次拉流失败')
						self.triggerEvent('RoomEvent', {
							tag: 'error',
							code: e.detail.code,
							detail: '多次拉流失败'
						});
						break;
					};
			}
		},

		onMainPlayError(e) {
			console.log('===> onMainPlayError: ', e)
		},
		onRoomDestroy(e) {
			console.log('onRoomDestroy: e=', e)
			_this && _this.triggerEvent('RoomEvent', {
				tag: 'roomClosed',
				code: -9006,
				detail: '房间已经解散了'
			})
		},
		onRecvRoomTextMsg(ret) {
			var self = _this;
			console.log("onRecvRoomTextMsg called, ret: ", ret)
			// ret.message = ret.message.resplace(/web端暂不支持undefined消息/, '')
			// 触发标签(mlvb-live-room )事件，收到消息 -2.7(文本聊天消息)
			self.triggerEvent('RoomEvent', {
				tag: 'recvTextMsg',
				code: 0,
				detail: ret
			})
		},
		onSketchpadData(ret) {
			var self = _this;
			console.log("onSketchpadData called, ret: ", ret)
			self.triggerEvent('RoomEvent', {
				tag: 'sketchpadData',
				code: 0,
				detail: ret
			})
		}
	},
	attached: function() {
		console.log('ready() called')
		// 保持屏幕常亮
		wx.setKeepScreenOn({
			keepScreenOn: true
		})
		var self = this;
		_this = this;
		var accountInfo = wx.getStorageSync('accountInfo')
		// self.data.isCaster = wx.getStorageSync('user_id') == wx.getStorageSync('liveAnchorID') ? 'anchor' : 'audience'
		self.data.roomID = wx.getStorageSync('liveRoomID');
		self.setData({
			isCaster: wx.getStorageSync('user_id') == wx.getStorageSync('liveAnchorID') ? true : false,
			userID: accountInfo.userID,
			userName: accountInfo.userName,
			unload: 0,
			// members:[{}, {}, {}]
		})
		console.log(self)


		wx.setStorageSync('streamIdArray', [])
	},

	detached: function() {
		console.log('detached() called')
		var self = this;
		_this = null;
		self.stop();
	},
	
})
